package com.manger.utils;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class SevenZipUtils {

    public static List<File> unzip(String zipPath, String destDir) throws Exception{
        List<File> fileList = new ArrayList<>();
        FileOutputStream fileOutputStream = null;
        SevenZFile sevenZFile = new SevenZFile(new File(zipPath));
        ArchiveEntry archiveEntry = null;
        while ( ( archiveEntry = sevenZFile.getNextEntry() ) != null ){
            if(archiveEntry.isDirectory()){
                continue;
            }
            File outFile = new File(destDir , archiveEntry.getName());

            if(!outFile.getParentFile().exists()){
                outFile.getParentFile().mkdirs();
            }
            System.out.println("create before: " + outFile.getName());
            outFile.createNewFile();
            System.out.println("create after: " + outFile.getName());
            byte[] content = new byte[(int)archiveEntry.getSize()];
            sevenZFile.read(content,0,content.length);
            fileOutputStream = new FileOutputStream(outFile);
            fileOutputStream.write(content);
            fileOutputStream.close();
            System.out.println("write after: " + outFile.getName());
            fileList.add(outFile);
        }
        return fileList;
    }

    public static void main(String[] args) throws Exception {
        String srcDir = "C:\\Users\\liuhj\\Desktop\\test\\test.7z";
        String destDir = "C:\\Users\\liuhj\\Desktop\\1111";
        SevenZipUtils.unzip(srcDir,destDir);
    }
}
